package com.idrive.listener;

import java.util.Locale;
import java.util.Map;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.telephony.SmsMessage;
import android.widget.Toast;

import com.idrive.database.DatabaseUtility;
import com.idrive.database.dao.CommonDataDao;
import com.idrive.database.dao.PhoneBookDao;
import com.idrive.database.dto.CommonData;

public class IDriveSmsListener extends BroadcastReceiver implements OnInitListener {

	private TextToSpeech textToSpeech;
	private Context context;

	public IDriveSmsListener(Context context) {
		this.context = context;
		textToSpeech = new TextToSpeech(context, this);
	}

	@Override
	public void onReceive(Context context, Intent intent) {

		if (isIDriveRunning()) {

			CommonDataDao commonDataDao = new CommonDataDao(context);
			CommonData commonData = commonDataDao.getCommonData();

			String option = commonData.getReadSms();

			if (!DatabaseUtility.SMS_READER_OPTION_INACTIVE.equals(option)) {

				if (intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
					Bundle bundle = intent.getExtras(); // ---get the SMS message passed in---
					SmsMessage[] msgs = null;

					if (bundle != null) {
						// ---retrieve the SMS message received---
						try {
							Object[] pdus = (Object[]) bundle.get("pdus");
							msgs = new SmsMessage[pdus.length];
							for (int i = 0; i < msgs.length; i++) {
								msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
								String number = msgs[i].getOriginatingAddress();
								String message = msgs[i].getMessageBody();

								if (DatabaseUtility.SMS_READER_OPTION_PHONEBOOK.equals(option)) {

									PhoneBookDao dao = new PhoneBookDao(context);
									Map<String, String> map = dao.getContacts();

									if (map.containsKey(number)) {
										readSms(message);
									}

								} else {
									readSms(message);
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
							Toast.makeText(context, e.toString(), Toast.LENGTH_LONG).show();
						}
					}
				}
			}
		}
	}

	public void onInit(int status) {
		textToSpeech.setLanguage(Locale.US);
	}

	private void readSms(String message) {
		textToSpeech.speak(message, TextToSpeech.QUEUE_FLUSH, null);
	}

	private boolean isIDriveRunning() {
		ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
			if ("com.idrive.service.IDriveService".equals(service.service.getClassName())) {
				return Boolean.TRUE;
			}
		}
		return Boolean.FALSE;
	}
}
